/**
 * 
 */
package com.jbat.gwt.tiledmapcreator.client.views;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.DragStartEvent;
import com.google.gwt.event.dom.client.DragStartHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;

import java.util.List;

/**
 * 
 */
public class TileSetViewImpl extends Composite implements TileSetView {

  interface TileSetViewImplUiBinder extends UiBinder<Widget, TileSetViewImpl> {
  }

  private static TileSetViewImplUiBinder uiBinder = GWT.create(TileSetViewImplUiBinder.class);

  private Presenter presenter;

  @UiField
  FlexTable tileTable;

  public TileSetViewImpl() {
    // sets the FlexTable tileTable
    initWidget(uiBinder.createAndBindUi(this));
  }

  /*
   * (non-Javadoc)
   * 
   * @see com.jbat.gwt.tiledmapcreator.client.views.TileSetView#setTileSet(java .lang.String)
   */
  @Override
  public void setData(List<String> imageUrlList) {
    // create the images
    for (String imageUrl : imageUrlList) {
      final Image imageFromUrl = new Image(imageUrl);
      imageFromUrl.setPixelSize(50, 50);
      addImageToTable(imageFromUrl);

      imageFromUrl.getElement().setDraggable(Element.DRAGGABLE_TRUE);
      imageFromUrl.addDragStartHandler(new DragStartHandler() {

        @Override
        public void onDragStart(DragStartEvent event) {
          event.setData("text/plain", imageFromUrl.getUrl());
          Element element = imageFromUrl.getElement();
          event.getDataTransfer().setDragImage(element, 0, 0);
        }
      });
    }
  }

  /*
   * (non-Javadoc)
   * 
   * @see com.jbat.gwt.tiledmapcreator.client.views.TileSetView#setPresenter(com
   * .jbat.gwt.tiledmapcreator.client.views.TileSetView.Presenter)
   */
  @Override
  public void setPresenter(Presenter presenter) {
    this.presenter = presenter;
  }

  private void addImageToTable(Image imageFromUrl) {
    int numRows = tileTable.getRowCount();
    tileTable.setWidget(numRows, 0, imageFromUrl);
  }

}
